from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *


# Create your views here.


class TypeView(APIView):
    def post(self, request):
        data = request.data
        res = TypeSer(data=data)
        if res.is_valid():
            res.save()
            return Response({'msg': 'OK', 'code': 200})

        return Response({'msg': res.errors, 'code': 400})

    def get(self, request):
        set = TypeModel.objects.all()
        ser = TypeSer(set, many=True).data
        return Response(ser)

    def delete(self, request):
        type_id = request.GET.get('type_id')
        type_set = TypeModel.objects.filter(id=type_id)
        if type_set:
            type_set.delete()
            return Response({'msg': 'OK', 'code': 200})
        else:
            return Response({'msg': 'NO', 'code': 400})


class AdvView(APIView):
    def get(self, request):
        type_id = request.GET.get('type_id')
        cate_id = request.GET.get('cate_id')
        level = request.GET.get('level')
        if cate_id:
            set = AdvModel.objects.filter(type_id=type_id, cate_id=cate_id)
        else:
            set = AdvModel.objects.filter(type_id=type_id, cate_id=None)
        ser = AdvSer(set, many=True).data
        return Response(ser)

    def post(self, request):
        data = request.data
        ser = AdvSer(data=data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': 'OK', 'code': 200})
        else:
            return Response({'msg': ser.errors, 'code': 400})


class IndexView(AdvView):
    def get(self, request):
        cate = AdvModel.objects.filter(type_id=1, cate=None)
        adv = AdvModel.objects.filter(type_id=2, cate=None)
        dcd = AdvModel.objects.filter(type_id=3, cate=None)
        psd = AdvModel.objects.filter(type_id=4, cate=None)
        data = {
            'cate_list': AdvCate1Ser(cate, many=True).data,
            'adv_list': AdvCate1Ser(adv, many=True).data,
            'dcd_list': AdvCate1Ser(dcd, many=True).data,
            'psd_list': AdvCate1Ser(psd, many=True).data
        }
        return Response(data)
